package com.managerConsummer.interceptor;

import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import util.JWTUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * The type Jwt interceptor.
 */
public class JwtInterceptor implements HandlerInterceptor {

    /**
     * The Logger.
     */
    public Logger logger = Logger.getLogger(this.getClass());
    /**
     * The Jwt util.
     */
    @Autowired
    private JWTUtil jwtUtil;

    /**
     * Pre handle boolean.
     *
     * @param request  the request
     * @param response the response
     * @param handler  the handler
     * @return the boolean
     * @throws Exception the exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String authorization = request.getHeader("Authorization");

        logger.debug("进了拦截器");
        logger.debug("Authorization:" + authorization);

        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Headers", "Authorization" +
                "WG-App-Version, WG-Device-Id, WG-Network-Type, WG-Vendor, WG-OS-Type, WG-OS-Version, WG-Device-Model, WG-CPU, WG-Sid, WG-App-Id, WG-Token,content-type");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET");
        response.setHeader("Access-Control-Allow-Credentials", "true");

        if (!StringUtils.isEmpty(authorization)) {
            logger.info("token 不为空:" + authorization);
            try {
                Claims claims = jwtUtil.parseJWT(authorization);
                logger.debug("token 验证通过");
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                logger.error("token 失效");
                return false;
            }
        } else {
            logger.debug("token不存在");
            return false;
        }
    }
}
